from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.filters import OrderingFilter, SearchFilter  # 排序
from django_filters.rest_framework import DjangoFilterBackend

# Create your views here.
from course import models, serializer
from course.filters import CourseFilterSet
from course.paginations import PageNumberPagination


class CourseCategoryView(GenericViewSet, ListModelMixin):
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = serializer.CourseCategorySerializer


class CourseView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = serializer.CourseModelSerializer
    pagination_class = PageNumberPagination

    # # 过滤和排序
    ordering_fields = ['id', 'price', 'students']
    # filter_backends = [OrderingFilter, SearchFilter]
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    search_fields = ['id', 'name', 'brief', 'students']
    filter_fields = ['course_category']  # 第一种过滤，指定字段

    # 过滤类:分类过滤，区间过滤
    # 通过django-filter扩展过滤 还是要配置filter_backends = [DjangoFilterBackend]
    # filter_backends = [DjangoFilterBackend]
    # 原来是配置字段，现在是配置类
    # filter_class = CourseFilterSet  # 第二种过滤 配置类  支持区间过滤


# 课程章节接口
class CourseChapterView(GenericViewSet, ListModelMixin):
    queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True)
    serializer_class = serializer.CourseChapterSerializer

    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']  # django-filter支持外键通过外键来过滤


# 按名字查询课程接口
class CourseSearchView(GenericViewSet, ListModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True)
    serializer_class = serializer.CourseModelSerializer

    pagination_class = PageNumberPagination

    filter_backends = [SearchFilter]
    search_fields = ['name']